#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include "../../board.h"
#include "lv_conf.h"
#include "backlight.h"

static int backlight_valid = 0;
static int backlight_level_cur = 0;
static int backlight_level_last = 0;

void lcd_backlight_valid(void)
{
    backlight_valid  = 1;
    cplog_printf("lcd_backlight_valid\n");
    lcd_backlight(backlight_level_cur);
}

void lcd_backlight_valid_for_silent_reset(void)
{
    backlight_valid = 1;
#if USE_SDK_API
    BOOL status = GetBacklightStatusBeforeReset();
    cplog_printf("lcd_backlight_valid_for_silent_reset[%d]: %d\n", status, backlight_level_cur);
    if(status) {
        lcd_backlight(backlight_level_cur);
    }
#endif
}

void lcd_backlight(int level)
{
    cplog_printf("lcd_backlight [%d]: %d\n", backlight_valid, level);
    if(backlight_valid) {
        lcd_backlight_ctrl(level);
    }

    backlight_level_cur = level;
    if(level > 0) {
        backlight_level_last = level;
    }
}

void lcd_backlight_toggle(void)
{
    if(backlight_level_cur <= 0) {
        lcd_backlight_on();
    } else {
        lcd_backlight_off();
    }
}

void lcd_backlight_on(void)
{
    if(backlight_level_last == 0) {
        backlight_level_last = 3;
    }
    lcd_backlight(backlight_level_last);
}

void lcd_backlight_off(void)
{
    lcd_backlight(0);
}

int lcd_backlight_status(uint8_t *onoff, uint8_t *level)
{
    if(onoff != NULL) {
        *onoff = GetBacklightStatusBeforeReset();
    }
    if(level != NULL) {
        *level = GetBacklightLevelBeforeReset();
    }
    return 0;
}
